define('apps/common/FriendOpts', ['core/jQuery', 'core/ajax/Ajax', 'apps/Dialog/Confirm', 'apps/Dialog/Tip', 'apps/common/UserData', 'core/Toggle', 'core/AsyncLoader'], function(require) {
    
    var $ = require('core/jQuery'),
        Confirm = require('apps/Dialog/Confirm'),
        Tip = require('apps/Dialog/Tip'),
        UserData = require('apps/common/UserData'),
		AsyncLoader = require('core/AsyncLoader'),
		Toggle = require('core/Toggle'),
		Ajax = require('core/ajax/Ajax'),
        
        Word = {
            'GNAME_EMPTY' : '分组名称不能为空'
        },
        
        URL = {
            'fgroupnew' : '/friend/ajax/group_new.php',
            'friendsetgroup' : '/friend/ajax/friend_set_group.php',
            'blacklist' : '/friend/ajax/blacklist_new.php'
        },
        
        TPL = {
            'optsdrop' : '<div style="right:0px;" class="abs ui_list list_set _j_optsdropcnt dni z_high">\
                            <ul class="ui_list_bd">\
                                <li><a href="#" class="_j_mail">私信</a></li>\
                                <li><a href="#" class="_j_frecommend">推荐</a></li>\
                                <li><a href="#" class="_j_remark _j_focused dni">备注</a></li>\
                                <li class="title _j_focused dni"><div class="ui_list_title">设置分组</div></li>\
                                <li class="set_group _j_focused dni list_circle">\
                                    <div class="set_wrap _j_grouplistcnt">\
                                        <ul class="ui_list_bd _j_grouplist">{{=it.grouplist}}</ul>\
                                        <div class="ui_list_ft">\
                                            <input type="text" class="group_creat" placeholder="新分组"><a class="spr_icons i_addgroup _j_groupnew" href="#">创建</a>\
                                        </div>\
                                    </div>\
                                </li>\
                                <li class="ui_list_split"></li>\
                                <li><a href="#" class="_j_blacklist">拉黑</a></li>\
                                <li><a href="#" class="_j_report">举报</a></li>\
                            </ul>\
                        </div>'
        };
        
    function FriendOpts(opts) {
        this.context = 'body';
        this.triggerSelector = '._j_g_fopts';
        this.dropTPL = TPL.optsdrop;
        
        K.mix(this, opts);

        this.init();
    }
    
    FriendOpts.prototype = {
        
        'init' : function() {
            this.bindEvents();
        },
        
        'bindEvents' : function() {
            $(this.context).delegate(this.triggerSelector, 'click', $.proxy(this.showOptsDrop, this)); // 下拉
        },
        
        /**
         * toggle 好友操作下拉框
         */
        'showOptsDrop' : function(ev) {
            
            var target = $(ev.currentTarget);
            
            if(this.target) { // 将上次的target clicked状态清除
                this.target.children('a').removeClass('clicked');
            }
            
            // 判断上次点击的target与本次是否一致
            if(!this.target || this.target.get(0) !== target.get(0)) { // 不一致更改this.target
                this.target = target;
                this.target.children('a').addClass('clicked');
                if(!this.optsDropCnt) { // 如果还未创建drop，创建之
                    UserData.getFGroup($.proxy(this.createOptsDrop, this));
                } else {
                    this.setDropPosition(); // 重设下拉位置
                    this.setOptsChoice(); // 设置用户可点的选项（根据好友关系）
                    this.optsDropCnt.removeClass('dni');
                }
            } else {
                if(this.optsDropCnt.hasClass('dni')) {
                    this.target.children('a').addClass('clicked');
                    this.setOptsChoice(); // 设置用户可点的选项（根据好友关系）
                }
                this.optsDropCnt.toggleClass('dni');
            }
            
            ev.preventDefault();
        },
        
        /**
         * 创建好友操作下拉框
         */
        'createOptsDrop' : function(fgroup) {
            var _this = this,
                groupListHTML = K.map(fgroup, function(item) {
                    return '<li data-groupid="'+item.gid+'" class="_j_groupitem _j_optsitem"><a class="circle" href="#">'+item.gname+'&nbsp;<span class="c9 _j_gnum">'+item.num+'</span><i class="spr_icons i_circle"></i></a></li>';
                }).join('');
            
            this.optsDropCnt = $(doT.template(this.dropTPL)({'grouplist' : groupListHTML})).appendTo(this.context);
            this.setInGroup(); // 设置好友所在分组

            // 相关功能模块初始化
            this.initMail(); // 私信
            this.initFRecommend(); // 推荐好友
            this.initRemark(); // 备注
            this.initReport(); // 举报
            
            // 简单链接事件绑定
            this.optsDropCnt
                .delegate('._j_groupitem', 'click', $.proxy(this.setFGroup, this)) // 设置分组
                .delegate('._j_blacklist', 'click', $.proxy(this.blackList, this)) // 拉黑
                .delegate('._j_groupnew', 'click', $.proxy(this.newGroup, this)); // 创建新分组
            
            // 设置好友可点项目
            this.setOptsChoice();
            
            // 定位显示
            this.setDropPosition();
            this.optsDropCnt.removeClass('dni');
            
            // 点击图层外消失
            new Toggle({
                'trigger' : this.triggerSelector,
                'board' : this.optsDropCnt,
                'handler' : function() { 
                    this.board.addClass('dni');
                    _this.target.children('a').removeClass('clicked');
                }
            });
        },
        
        'setOptsChoice' : function() {
            var isfriend = this.target.data('isfriend');
            if(isfriend === 1 || isfriend === 3) { // 对于已关注的好友，需要显示备注、好友列表选项
                this.optsDropCnt.find('._j_focused').removeClass('dni');
            } else {
                this.optsDropCnt.find('._j_focused').addClass('dni');
            }
        },
        
        /**
         * 定位
         */
        'setDropPosition' : function() {
            var targetOffset = this.target.offset();
            this.optsDropCnt.css({
                'top' : targetOffset.top + this.target.outerHeight(),
                'left' : targetOffset.left - this.optsDropCnt.outerWidth() + this.target.outerWidth()
            });
        },
        
        /**
         * 设置该好友属于的分组
         */
        'setInGroup' : function() {
            var groups = String.prototype.split.call(this.target.data('ingroup') || '', ','),
                groupList = this.optsDropCnt.find('._j_groupitem');
            
            groupList.removeClass('belong');
            K.forEach(groups, function(groupid) {
                groupList.filter('[data-groupid="'+groupid+'"]').addClass('belong');
            });
        },
        
        'initRemark' : function() {
            new AsyncLoader({
                'context' : this.optsDropCnt,
                'triggerSelector' : '._j_remark',
                'modules' : ['apps/Dialog/Remark'],
                'handler' : $.proxy(function(Remark) {
                    var target = this.target;
                    Remark({'uid':target.data('fuid'), 'uname':target.data('funame')});
                }, this)
            });
        },
        
        'initReport' : function() {
            new AsyncLoader({
                'context' : this.optsDropCnt,
                'triggerSelector' : '._j_report',
                'modules' : ['apps/Dialog/ReportUser'],
                'handler' : $.proxy(function(ReportUser) {
                    var target = this.target;
                    ReportUser({'uid':target.data('fuid'), 'uname':target.data('funame')});
                }, this)
            });
        },
        
        'initMail' : function() {
            var target = this.target;
            this.optsDropCnt.find('._j_mail').data('touser', {'type':0, 'id':target.data('fuid'), 'name':target.data('funame'), 'isfriend':target.data('isfriend')});
            new AsyncLoader({
                'context' : this.optsDropCnt,
                'triggerSelector' : '._j_mail',
                'modules' : ['apps/Dialog/Mail'],
                'handler' : $.proxy(function(Mail) {
                    new Mail({'context' : this.optsDropCnt, 'triggerSelector' : '._j_mail'});
                }, this)
            });
        },
        
        'initFRecommend' : function() {
            var target = this.target;
            this.optsDropCnt.find('._j_frecommend').data('touser', {'type':0, 'id':target.data('fuid'), 'name':target.data('funame')});
            new AsyncLoader({
                'context' : this.optsDropCnt,
                'triggerSelector' : '._j_frecommend',
                'modules' : ['apps/Dialog/FRecommend'],
                'handler' : $.proxy(function(FRecommend) {
                    new FRecommend({'context' : this.optsDropCnt, 'triggerSelector' : '._j_frecommend'});
                }, this)
            });
        },
        
        /**
         * 新建分组
         */
        'newGroup' : function(ev) {
            var input = $(ev.currentTarget).prev(),
                groupName = $.trim(input.val());
            if(groupName !== '') {
                Ajax.post(URL.fgroupnew, 
                	{'gname' : groupName},
	                $.proxy(function(data) {
                        this.optsDropCnt.find('._j_grouplist').append('<li data-groupid="'+data.gid+'" class="_j_groupitem _j_optsitem"><a class="circle" href="#">'+groupName+'&nbsp;<span class="c9 _j_gnum">0</span><i class="spr_icons i_circle"></i></a></li>');
                        //this.fgroupScrollbar.fire('contentchange');
                        input.val('');
                        UserData.addFGroup({'gid':data.gid, 'gname':groupName, 'num':0});
	                }, this),
	                $.proxy(function(error) {
	                    K.log('Err Data:', error);
	                }, this)
                );
            } else {
                alert('分组名不能为空');
            }
            ev.preventDefault();
        },

        /**
         * 设置好友所属分组
         */
        'setFGroup' : function(ev) {
            var target = $(ev.currentTarget),
                action, gnumIncrease;
                
            // 确定加入移除的动作及分组数目变化量
            if(!target.hasClass('belong')) {
                action = 1, gnumIncrease = 1;
            } else {
                action = 0, gnumIncrease = -1;
            }
            
            // 设置分组
            Ajax.post(URL.friendsetgroup, 
            	{'fuid':this.target.data('fuid'), 'gid':target.data('groupid'), 'action':action}, 
            	function(data) {
                    var gnum = parseInt(target.find('._j_gnum').text(), 10);
                    target.find('._j_gnum').text(gnum + gnumIncrease);
            	},
            	function(error) {
	                K.log('Data Err:', error);
            	}
            );
            ev.preventDefault();
        },
        
        'blackList' : function(ev) {
            var target = this.target;
            Confirm({
                'content' : '<div class="pop_alert tac rel" style="padding-top:56px;height:71px;">\
                                <span class="infor">\
                                          确定将<a href="/'+target.data('fuid')+'">'+target.data('funame')+'</a>拉入黑名单吗？<br><br>\
                                          拉黑后，你们将自动解除关注关系，并且<br>\
                                          她不能再关注你，不能给你评论、发私信\
                                </span>\
                            </div>'
            }, $.proxy(function() {
                Ajax.post(URL.blacklist, 
                	{'fuid':target.data('fuid')}, 
	                function(data) {
                        new Tip({
                            'style' : 360,
                            'autoHide' : true,
                            'content' : '<div style="width:340px;height:100px;padding-top:70px;" class="pop_alert tac rel">\
                                            <span class="infor">\
                                                <i class="spr_icons i_ok_m"></i>&nbsp;拉黑成功\
                                            </span>\
                                        </div>'
                        });
	                },
	                function(error) {
                        K.log('Err Data:', error);
	                }
	            );
            }, this));
            ev.preventDefault();
        }
    };

    return FriendOpts;
});